package org.fordprefect.struts2lightboxplugin.util;

import org.apache.log4j.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: milmber
 * Date: Sep 10, 2007
 * Time: 10:42:09 AM
 * To change this template use File | Settings | File Templates.
 */
public class FileUtil {

    private static Logger log = Logger.getLogger(FileUtil.class);

    public static String formatThumbNailName(String name, int width, int height) {
        String[] parts = name.split("\\.");
        StringBuffer buff = new StringBuffer();
        if (parts.length == 1) {
            buff.append(name);
            buff.append("_");
            buff.append(width);
            buff.append("x");
            buff.append(height);
        } else {
            for (int i=0;i<parts.length;i++) {
                if (i == parts.length-2) {
                    buff.append(parts[i]);
                    buff.append("_");
                    buff.append(width);
                    buff.append("x");
                    buff.append(height);
                    buff.append(".");
                } else {
                    buff.append(parts[i]);
                }
                if (i < parts.length-2) {
                    buff.append(".");
                }
            }
        }
        log.debug("ThumbNail Name: " + buff.toString());
        return buff.toString();
    }

    public static String extractImageName(String imageURL) {
        int lastPathDelimiter = imageURL.lastIndexOf(System.getProperty("file.separator"));
        String imageName = imageURL;
        if (lastPathDelimiter != -1) {
            imageName = imageURL.substring(lastPathDelimiter+1, imageURL.length());
        }
        log.debug("Image Name: " + imageName);
        return imageName;
    }

    public static String getRelativeURI(String contextPath) {
        log.debug("Context Path: " + contextPath);
        if (contextPath.startsWith("/")) {
            contextPath = contextPath.substring(1, contextPath.length());
        }
        int lastSlash = contextPath.lastIndexOf("/");
        if (lastSlash != -1) {
            return contextPath.substring(0, lastSlash);
        } else return "";
    }

    public static String getRealPath(String dir) {
        log.debug("Real Path: " + dir);
        return dir.substring(0, dir.lastIndexOf(System.getProperty("file.separator")));
    }

    public static String extractImageDirectory(String imageURL) {
        int lastPathDelimiter = imageURL.lastIndexOf(System.getProperty("file.separator"));
        String imagePath = "";
        if (lastPathDelimiter != -1) {
            imagePath = imageURL.substring(0, lastPathDelimiter);
        }
        log.debug("Image Path: " + imagePath);
        return imagePath;
    }

}
